package com.hundsun.yr.universal.library.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;

import com.hundsun.yr.universal.library.R;
import com.hundsun.yr.universal.library.common.DensityUtils;
import com.hundsun.yr.universal.library.utils.MathUtils;

import java.util.Set;


/**
 * @version V1.0
 * @Title: HSEditText.java
 * @Description: 普通输入框
 * @date 2015-11-30 上午10:19:58
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
@SuppressLint("ClickableViewAccessibility")
public class HSEditText extends EditText implements OnFocusChangeListener, TextWatcher {


    private int before_selection;
    private boolean ISDELETE;

    /*判断是否为手机号3-4-4显示，或者银行卡4-4-4显示*/
    public static enum HSInputType {
        NONE,
        MONEY,
        PHONE,
        BANKCARD;

        public static HSInputType input_none = HSInputType.NONE;

        public static HSInputType getDefaultType() {
            return input_none;
        }

    }

    private HSInputType mInputType = HSInputType.getDefaultType();

    /**
     * 右边按钮的引用（默认为删除按钮）
     */
    protected Drawable mRightDrawable;
    /**
     * 左边图标的引用
     */
    private Drawable mLeftDrawable;

    /**
     * 缩放系数
     */
    private float leftScal = 0;
    /**
     * 缩放系数
     */
    private float rightScal = 0;

    /**
     * hint文字颜色
     */
    private int hintTextColor = -1;
    /**
     * hint文字字体大小
     */
    private int hintTextSize = 0;

    private boolean canStartWithZero = true;

    private int rightWidth = 0;
    private int rightHeight = 0;


    /* 每组的长度 */
    private Integer eachLength = 4;
    /* 分隔符 */
    private String delimiter = " ";

    private String text = "";

    private String maxValue = "";

    public HSEditText(Context context) {
        this(context, null);
    }

    public HSEditText(Context context, AttributeSet attrs) {
        // 这里构造方法也很重要，不加这个很多属性不能再XML里面定义
        this(context, attrs, android.R.attr.editTextStyle);
    }

    public HSEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    @SuppressWarnings("deprecation")
    private void init(Context context, AttributeSet attrs) {


        // 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
//		mRightDrawable = getCompoundDrawables()[2];

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HSEditText);

        hintTextColor = a.getColor(R.styleable.HSEditText_hs_et_hintTextColor, getResources().getColor(R.color.text_cc));

        if (a.hasValue(R.styleable.HSEditText_hs_et_hintTextSize)) {
            hintTextSize = a.getInt(R.styleable.HSEditText_hs_et_hintTextSize, 14);
        }

        if (a.hasValue(R.styleable.HSEditText_hs_et_can_start_with_zero)) {
            canStartWithZero = a.getBoolean(R.styleable.HSEditText_hs_et_can_start_with_zero, true);
        }

        if (a.hasValue(R.styleable.HSEditText_hs_et_maxValue)) {
            maxValue = a.getString(R.styleable.HSEditText_hs_et_maxValue);
        }

        if (a.hasValue(R.styleable.HSEditText_hs_et_left_drawable)) {
            mLeftDrawable = a.getDrawable(R.styleable.HSEditText_hs_et_left_drawable);
        }

        if (a.hasValue(R.styleable.HSEditText_hs_et_right_drawable)) {
            mRightDrawable = a.getDrawable(R.styleable.HSEditText_hs_et_right_drawable);
        } else {
//        	if (mRightDrawable == null) {
//        		mRightDrawable = getResources().getDrawable(R.drawable.icon_delete);
//    		}
        }

        if (a.hasValue(R.styleable.HSEditText_have_et_right_drawable)) {
            if (mRightDrawable == null) {
                mRightDrawable = getResources().getDrawable(R.drawable.icon_delete);
            }
        } else {
            mRightDrawable = null;
        }

        if (a.hasValue(R.styleable.HSEditText_hs_et_hsInputtype)) {
            int hsInputtype = a.getInt(R.styleable.HSEditText_hs_et_hsInputtype, 0);
            setHSInputType(hsInputtype);
        }

        a.recycle();

        setQueryHint(getHint());
        setOnFocusChangeListener(this);
        addTextChangedListener(this);
        setSingleLine();
        setInputType(getInputType());
    }

    public void setCustomPadding(int left, int top, int right, int bottom) {
        setPadding(left, top, right, bottom);
    }


    /**
     * 设置左侧图片
     *
     * @param drawable
     */
    public void setLeftDrawable(Drawable drawable) {
        mLeftDrawable = drawable;
        invalidate();
    }

    /**
     * 设置右侧图片
     *
     * @param drawable
     */
    public void setRightDrawable(Drawable drawable) {
        mRightDrawable = drawable;
        invalidate();

    }

    /**
     * 设置hint文字
     *
     * @param hint
     */
    public void setQueryHint(CharSequence hint) {
        updateQueryHint(hint);
    }


    /**
     * 设置hint文字颜色
     *
     * @param hint
     */
    public void setQueryHintColor(int color) {
        hintTextColor = color;
        updateQueryHint(getHint());
    }

    /**
     * 设置hint文字颜色
     *
     * @param color
     */
    private CharSequence getDecoratedHint(CharSequence hintText) {
        Spannable ssb = new SpannableString(hintText);
        if (hintTextColor == -1) {
            return ssb;
        }
        ssb.setSpan(new ForegroundColorSpan(hintTextColor), 0, hintText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (hintTextSize > 0) {
            ssb.setSpan(new AbsoluteSizeSpan(hintTextSize, true), 0, hintText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return ssb;
    }

    private void updateQueryHint(CharSequence hint) {
        if (hint != null) {
            setHint(getDecoratedHint(hint));
        } else {
            setHint(getDecoratedHint(""));
        }
    }

    /**
     * 因为我们不能直接给EditText设置点击事件，所以我们用记住我们按下的位置来模拟点击事件 当我们按下的位置 在 EditText的宽度 -
     * 图标到控件右边的间距 - 图标的宽度 和 EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标，竖直方向没有考虑
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (getCompoundDrawables()[2] != null) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (mRightDrawable != null) {
                    boolean touchable = event.getX() > (getWidth() - getPaddingRight() - mRightDrawable.getIntrinsicWidth()) && (event.getX() < ((getWidth() - getPaddingRight())));
                    if (touchable) {
                        this.setText("");
                    }
                }

            }
        }

        return super.onTouchEvent(event);
    }

    /**
     * 当ClearEditText焦点发生变化的时候，判断里面字符串长度设置清除图标的显示与隐藏
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            // 设置焦点
            setSelection(getText().toString().length());
            setRightIconVisible(getText().length() > 0);
        } else {
            setRightIconVisible(false);
        }
    }

    /**
     * 设置右侧图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     *
     * @param visible
     */
    public void setRightIconVisible(boolean visible) {
        Drawable right = visible ? mRightDrawable : null;
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
        setCompoundDrawablePadding((int) getResources().getDimension(R.dimen.grid));
    }

    /**
     * 设置左侧图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     *
     * @param visible
     */
    public void setLeftIconVisible() {

        Drawable left = mLeftDrawable;
        setCompoundDrawables(left, getCompoundDrawables()[1], getCompoundDrawables()[2], getCompoundDrawables()[3]);
        setCompoundDrawablePadding((int) getResources().getDimension(R.dimen.grid));
    }


    /**
     * 当输入框里面内容发生变化的时候回调的方法
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {

        if (!canStartWithZero) {
            if (s.toString().equals("0") || s.toString().startsWith("0")) {
                this.setText("");
            }
        }

        setRightIconVisible(s.length() > 0);
        if (mInputType == HSInputType.PHONE) {
            division(s,start,count);
        } else if (mInputType == HSInputType.BANKCARD){
            division(s.toString(), count);
        }
        if (maxValue != "" && s.length() > 0) {
            validate(s.toString());
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        if (mInputType == HSInputType.MONEY) {
            division(s);
        }


    }


    /**
     * 设置晃动动画
     */
    public void setShakeAnimation() {
        this.setAnimation(shakeAnimation(5));
    }

    /**
     * 晃动动画
     *
     * @param counts 1秒钟晃动多少下
     * @return
     */
    public static Animation shakeAnimation(int counts) {
        Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(counts));
        translateAnimation.setDuration(1000);
        return translateAnimation;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        // TODO Auto-generated method stub
        super.onLayout(changed, left, top, right, bottom);

        int height = getMeasuredHeight();


        if (mLeftDrawable != null) {
            if (leftScal == 0) {
                leftScal = (float) ((0.6 * height) / mLeftDrawable.getIntrinsicHeight());
                mLeftDrawable.setBounds(0, 0, (int) (mLeftDrawable.getIntrinsicWidth() * leftScal), (int) (mLeftDrawable.getIntrinsicHeight() * leftScal));
                setLeftIconVisible();
            }
        }


        if (mRightDrawable != null) {
            if (rightScal == 0) {

                if (DensityUtils.dp2px(getContext(), 24) < height) {
                    if (DensityUtils.dp2px(getContext(), 24) < mRightDrawable.getIntrinsicHeight()) {
                        rightScal = (float) (DensityUtils.dp2px(getContext(), 24)) / mRightDrawable.getIntrinsicHeight();
                    } else {
                        rightScal = (float) (0.4 * height) / mRightDrawable.getIntrinsicHeight();
                        ;
                    }
                } else {
                    rightScal = (float) (0.4 * height) / mRightDrawable.getIntrinsicHeight();
                }
                rightWidth = (int) (mRightDrawable.getIntrinsicWidth() * rightScal);
                rightHeight = (int) (mRightDrawable.getIntrinsicHeight() * rightScal);

                mRightDrawable.setBounds(0, 0, rightWidth, rightHeight);
                setRightIconVisible(false);
            }
        }

    }

    /**
     * 获取右侧图标宽度
     *
     * @return
     */
    public int getRightWidth() {
        return rightWidth;

    }

    /**
     * 获取右侧图标高度
     *
     * @return
     */
    public int getRightHeight() {
        return rightHeight;

    }


    /**
     * 得到每组个数
     */
    public Integer getEachLength() {
        return eachLength;
    }

    /**
     * 设置每组个数
     */
    public void setEachLength(Integer eachLength) {
        this.eachLength = eachLength;
    }

    /**
     * 得到间隔符
     */
    public String getDelimiter() {
        return delimiter;
    }

    /**
     * 设置间隔符
     */
    public void setDelimiter(String delimiter) {
        this.delimiter = delimiter;
    }

    /**
     * 获取银行卡号
     *
     * @return 去空格之后的卡号
     */
    public String getBank() {
        return getText().toString().replace(" ", "");
    }

    /**
     * 获取手机号
     *
     * @return 去空格之后的手机号
     */
    public String getPhone() {
        return getText().toString().replace(" ", "");
    }


    /**
     * 设置初始值
     *
     * @param content
     */
    public void setFirstText(String content) {
        division(content, 0);
    }


    /**
     * 设置输入类型
     *
     * @param type
     */
    public void setHSInputType(HSInputType type) {

        mInputType = type;
    }

    /**
     * 设置输入类型
     *
     * @param type
     */
    public void setHSInputType(int type) {

        switch (type) {
            case 0:
                mInputType = HSInputType.NONE;
                break;
            case 1:
                mInputType = HSInputType.MONEY;
                break;
            case 2:
                mInputType = HSInputType.PHONE;
                break;
            case 3:
                mInputType = HSInputType.BANKCARD;
                break;
            default:
                break;
        }

    }

    /**
     * 获取输入类型
     *
     * @param type
     */
    public HSInputType getHSInputType() {

        return mInputType;
    }

    /**
     * 分割字符串
     *
     * @param content 字符串内容
     * @param count   字符串长度
     */
    public void division(Editable s) {

        if (mInputType == HSInputType.NONE || TextUtils.isEmpty(s)) {
            return;
        }


        if (mInputType == HSInputType.MONEY) {
            String temp = s.toString();

            int posDot = temp.indexOf(".");
            if (posDot < 0)
                return;
            if (temp.length() - posDot - 1 > 2) {
                s.delete(posDot + 3, posDot + 4);
            } else {
                int lastposDot = temp.lastIndexOf(".");
                if (posDot != lastposDot) {
                    s.delete(lastposDot, lastposDot + 1);
                }
            }
        }
    }


    /**
     * 分割字符串
     *
     * @param content 字符串内容
     * @param count   字符串长度
     */
    public void division(String content, int count) {

        if (mInputType == HSInputType.NONE || TextUtils.isEmpty(content)) {
            return;
        }

        // 统计个数
        int len = content.length();

        if (len < eachLength) // 长度小于要求的数
            return;
        if (count > 1) {// 设置新字符串的时候，直接返回
            return;
        }
        // 如果包含空格，就清除
        char[] chars = content.replace(" ", "").toCharArray();
        len = chars.length;
        // 每4个分组,加上空格组合成新的字符串
        StringBuffer sb = new StringBuffer();
/*        if (mInputType == HSInputType.PHONE) {
            for (int i = 0; i < len; i++) {
                if (i < 6) {
                    if (i == 3) {
                        sb.append(" ");
                        sb.append(chars[i]);// 添加字符
                    } else {
                        sb.append(chars[i]);// 添加字符
                    }
                } else {
                    if ((i - 3) % eachLength == 0 && i != 0)// 每次遍历到4的倍数，就添加一个空格
                    {
                        sb.append(" ");
                        sb.append(chars[i]);// 添加字符
                    } else {
                        sb.append(chars[i]);// 添加字符
                    }
                }
            }
        } else */if (mInputType == HSInputType.BANKCARD) {
            for (int i = 0; i < len; i++) {
                if (i % eachLength == 0 && i != 0)// 每次遍历到4的倍数，就添加一个空格
                {
                    sb.append(" ");
                    sb.append(chars[i]);// 添加字符
                } else {
                    sb.append(chars[i]);// 添加字符
                }
            }
        }


        text = sb.toString();
        setText(text);
        setSelection(text.length());
    }

    public void division(CharSequence charSequence,int start, int before){
        char[] chars = charSequence.toString().replace(" ", "").toCharArray();
        int len = chars.length;

        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < len; i++) {
            if (i < 6) {
                if (i == 3) {
                    stringBuilder.append(" ");
                    stringBuilder.append(chars[i]);// 添加字符
                } else {
                    stringBuilder.append(chars[i]);// 添加字符
                }
            } else {
                if ((i - 3) % eachLength == 0 && i != 0)// 每次遍历到4的倍数，就添加一个空格
                {
                    stringBuilder.append(" ");
                    stringBuilder.append(chars[i]);// 添加字符
                } else {
                    stringBuilder.append(chars[i]);// 添加字符
                }
            }
        }

        String string = stringBuilder.toString();

        if (!string.equals(charSequence.toString())) {

            int index;
            if (charSequence.toString().endsWith(" ")){
                start = start - 2;
                index = start + 2;
            } else {
                index = start + 1;
            }
            if (start - 1 > 0 && start - 1 < string.length() && string.charAt(start - 1) == ' '){
                if (before == 1) {
                    index = start - 1;
                }
            } else if (string.charAt(start) == ' '){
                if (before == 0) {
                    index++;
                } else {
                    string = stringBuilder.replace(start - 1,start,"") + "";
                    index = start - 1;
                }
            } else {
                if (before == 1) {
                    index--;
                }
            }

            setText(string);
            setSelection(index);
        }else {
            if (start - 1 > 0 && start - 1 < string.length() && string.charAt(start - 1) == ' '){
                setSelection(start - 1);
            }
        }
    }

    /**
     * 判断是否小于最大值
     *
     * @param content
     */
    public void validate(String content) {
        if (content.endsWith("."))
            return;
        try {
            if (MathUtils.compare(content, maxValue) > 0) {// content>最大值
                text = content.substring(0, content.length() - 1);
                setText(text);
                setSelection(text.length());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
